#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define RANGE 100

int * arrGen(int number){
    if(number <= 0){
        return NULL;
    }
    int * array = (int*)malloc(sizeof(int) * number);
    if(array == NULL){
        printf("malloc failed.\n");
        return NULL;
    }
    srand(time(NULL));
    array[0] = rand()%RANGE;
    for(int i = 1;i < number;++i){
        array[i] = array[i-1] + (rand()%RANGE) + 1; // 递增数组
    }
    return array;
}
// 调整参数设置 让binarySearch函数变得更加灵活
int binarySearchHelp(int * array,int low,int high,int key){

    if(low > high){
        
        return -1;
    }
    int index=(low+high)/2;
    if(array[index] == key){
        
        return index;
    }else if(array[index] < key){

        return binarySearchHelp(array,index+1,high,key); 
    }
    return binarySearchHelp(array,low,index-1,key);
}

int binarySearch(int * array,int length,int key){

    return binarySearchHelp(array,0,length,key);
}

void printArray(int * array,int length){

    for(int i = 0;i < length;++i){

        printf("%d\t",array[i]);
    }
    printf("\n");
}

int main(int argc,char * argv[]){

    if(argc != 2){

        printf("need one position integer.\n");
        return EXIT_FAILURE;
    }
    int number = (int)strtol(argv[1],NULL,10);
    int * array = arrGen(number);
    printArray(array,number);
    int key = 0;
    for(int i = 0;i < number;++i){
        if(i%2 == 0){
            key = array[rand()%number];
        }else{

            key = rand()%RANGE;
        }
        printf("binarySearch %d, result = %d.\n",key,binarySearch(array,number,key));
    }
    free(array);
    return 0;
}



